import { R } from '@dataui/crud/crud';
import { getOwnPropNames } from '@nest-crud/utils';
import { CRUD_BASE_CONTROLLER_MD, IS_BASE_METHOD_MD } from '../constants';

export function CrudBaseController() {
  // eslint-disable-next-line @typescript-eslint/ban-types
  return (target: Function) => {
    const methods = target.prototype;
    const metadatas = {};
    getOwnPropNames(methods).forEach((name) => {
      const metadataKeys = Reflect.getMetadataKeys(methods[name]);
      if (metadataKeys.length) {
        metadatas[name] = {};
      }
      metadataKeys.forEach((i) => {
        metadatas[name][i] = Reflect.getMetadata(i, methods[name]);
        R.set(IS_BASE_METHOD_MD, true, methods[name]);
      });
    });
    R.set(CRUD_BASE_CONTROLLER_MD, metadatas, target);
  };
}
